package com.ympc.service.impl;

import com.ympc.mapper.StudentMapper;
import com.ympc.mapper.UsersMapper;
import com.ympc.pojo.Class;
import com.ympc.pojo.CourseVO;
import com.ympc.pojo.Student;
import com.ympc.pojo.Teacher;
import com.ympc.pojo.Users;
import com.ympc.service.ClassService;
import com.ympc.service.StudentService;
import com.ympc.service.TeacherService;
import com.ympc.service.UsersService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    
    @Resource
    private StudentMapper studentMapper;

    @Resource
    private UsersService usersService;
    
    @Resource
    private UsersMapper usersMapper;
    
    @Resource
    private ClassService classService;
    
    @Resource
    private TeacherService teacherService;
    
    @Override
    public List<Student> getAllStudents() {
        return studentMapper.findAll();
    }
    
    @Override
    public Student getStudentById(Integer id) {
        return studentMapper.findById(id);
    }
    
    @Override
    public Student getStudentByNumber(String studentNumber) {
        return studentMapper.findByStudentNumber(studentNumber);
    }
    
    @Override
    public Student getStudentByUserId(Integer userId) {
        return studentMapper.findByUserId(userId);
    }
    
    @Override
    public List<Student> getStudentsByClass(String className) {
        return studentMapper.findByClassName(className);
    }
    
    @Override
    public List<Student> getStudentsByStudentNumber(String studentNumber) {
        return studentMapper.findByStudentNumberLike(studentNumber);
    }
    
    @Override
    public List<Student> getStudentsByClassAndStudentNumber(String className, String studentNumber) {
        return studentMapper.findByClassNameAndStudentNumber(className, studentNumber);
    }
    
    @Override
    @Transactional
    public boolean addStudent(Student student) {
        try {
            // 1. 自动创建登录账号（使用学号作为用户名）
            Users user = usersService.createUser(
                student.getStudentNumber(),  // 用户名使用学号
                "123456",                    // 密码统一为123456
                student.getName(),           // 真实姓名
                "student"                    // 角色
            );
            
            if (user == null || user.getId() == null) {
                // 创建用户失败
                return false;
            }
            
            // 2. 设置学生的user_id
            student.setUserId(user.getId());
            
            // 3. 插入学生记录
            return studentMapper.insertStudent(student) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean updateStudent(Student student) {
        try {
            // 如果学生已有关联的用户，更新用户的真实姓名（如果姓名改变了）
            if (student.getUserId() != null) {
                Users user = usersService.getUserByUsername(student.getStudentNumber());
                if (user != null && user.getId().equals(student.getUserId())) {
                    // 用户名（学号）和关联ID匹配，更新真实姓名
                    // 注意：这里不更新用户名（学号），因为用户名改变会影响登录
                    // 如果需要更新用户名，需要更复杂的逻辑，暂时只更新姓名
                    // Users updateUser = new Users();
                    // updateUser.setId(user.getId());
                    // updateUser.setRlname(student.getName());
                    // usersService.updateUser(updateUser); // 如果实现了updateUser方法
                }
            }
            
            return studentMapper.updateStudent(student) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean deleteStudent(Integer id) {
        return studentMapper.deleteStudent(id) > 0;
    }
    
    @Override
    public boolean changePassword(Integer userId, String oldPassword, String newPassword) {
        // 验证旧密码
        Users dbUser = usersMapper.findById(userId);
        if (dbUser == null || !dbUser.getPassword().equals(oldPassword)) {
            return false;
        }
        // 更新密码
        return usersMapper.updatePassword(userId, newPassword) > 0;
    }
    
    @Override
    public List<CourseVO> getCoursesByStudentId(Integer studentId) {
        Student student = studentMapper.findById(studentId);
        if (student == null || student.getClassName() == null || student.getClassName().trim().isEmpty()) {
            return new ArrayList<>();
        }
        return getCoursesByClassName(student.getClassName());
    }
    
    @Override
    public List<CourseVO> getCoursesByStudentUserId(Integer userId) {
        Student student = studentMapper.findByUserId(userId);
        if (student == null || student.getClassName() == null || student.getClassName().trim().isEmpty()) {
            return new ArrayList<>();
        }
        return getCoursesByClassName(student.getClassName());
    }
    
    /**
     * 根据班级名称获取课程列表
     */
    private List<CourseVO> getCoursesByClassName(String className) {
        List<CourseVO> courses = new ArrayList<>();
        
        // 1. 根据班级名称找到所有班级
        List<Class> classes = classService.getClassesByClassName(className);
        
        // 2. 对每个班级，找到对应的教师及其科目
        for (Class clazz : classes) {
            if (clazz.getTeacherId() != null) {
                Teacher teacher = teacherService.getTeacherById(clazz.getTeacherId());
                if (teacher != null && teacher.getSubject() != null && !teacher.getSubject().trim().isEmpty()) {
                    CourseVO course = new CourseVO();
                    course.setSubject(teacher.getSubject());
                    course.setTeacherName(teacher.getRealName());
                    course.setCollege(teacher.getCollege());
                    course.setClassName(clazz.getClassName());
                    course.setMajor(clazz.getMajor());
                    course.setTeacherId(teacher.getId());
                    courses.add(course);
                }
            }
        }
        
        return courses;
    }
}

